package util;

import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class DButil {
    static Connection conn=null;
    static PreparedStatement ps = null;
    static ResultSet rs =null;
    private static Connection getconnection(){
        /**
         * 连接数据库
         */
        try {
            Properties pt = new Properties();
            pt.load(DButil.class.getClassLoader().getResourceAsStream("db.properties"));
            String url=pt.getProperty("url");
            String user=pt.getProperty("user");
            String pwd=pt.getProperty("pwd");
            String driver=pt.getProperty("driver");
            Class.forName(driver);
            conn=DriverManager.getConnection(url,user,pwd);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return conn;

    }
    //获取命令
    private   static void getpreparedstasement(String sql,Object...params){
        getconnection();
        try {
            ps=conn.prepareStatement(sql);
            if(params!=null){
                for (int i=0;i<params.length;i++){
                    ps.setObject(i+1,params[i]);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //查
    public  static ResultSet select(String sql,Object...params){
        getpreparedstasement(sql,params);
        try {
            rs=ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
    //增删改
    public static  int update(String sql,Object...params){
        int num=0;
        getpreparedstasement(sql,params);
        try {
           num= ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            allclose();
        }
        return num;
    }
    public static void allclose(){
        try {
            if (rs!=null)
                rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            rs=null;
        }

        try {
            if (ps!=null)
                ps.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            ps=null;
        }

        try {
            if (conn!=null)
                conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            conn=null;
        }

    }

}
